package com.nsi.o2o.service.impl;

import com.nsi.o2o.dao.ProductDao;
import com.nsi.o2o.dao.ProductImgDao;
import com.nsi.o2o.dto.ImageHolder;
import com.nsi.o2o.dto.ProductExecution;
import com.nsi.o2o.entity.Product;
import com.nsi.o2o.entity.ProductImg;
import com.nsi.o2o.enums.ProductStateEnum;
import com.nsi.o2o.exceptions.ProductOperationException;
import com.nsi.o2o.service.ProductService;
import com.nsi.o2o.util.ImageUtil;
import com.nsi.o2o.util.PageCalculator;
import com.nsi.o2o.util.PathUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: Luo Zhen
 * @date: 2018/9/18 17:44
 * @description:
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductDao productDao;
    @Autowired
    private ProductImgDao productImgDao;

    /**
     * 处理缩略图，获取缩略图相对路径并赋值给product
     * 往tb_product 写入商品信息，获取productId
     * 结合productId批量处理商品详情图
     * 将商品详情图列表插入tb_product_img
     *
     * @param product
     * @param thumbnail
     * @param productImgList
     * @return
     * @throws ProductOperationException
     */
    @Override
    @Transactional(rollbackFor = ProductOperationException.class)
    public ProductExecution addProduct(Product product, ImageHolder thumbnail, List<ImageHolder> productImgList) throws ProductOperationException {
        if (product != null && product.getShop() != null && product.getShop().getShopId() != null) {
            product.setCreateTime(new Date());
            product.setLastEditTime(new Date());
            //默认为上架的状态
            product.setEnableStatus(1);
            //若商品缩略图不为空则添加
            if (thumbnail != null) {
                addThumbnail(product, thumbnail);
            }
            try {
                int rowCount = productDao.insertProduct(product);
                if (rowCount == 0) {
                    throw new ProductOperationException("创建商品失败");
                }
            } catch (Exception e) {
                throw new ProductOperationException("创建商品失败:" + e.getMessage());
            }
            //添加批量图片
            if (productImgList != null && productImgList.size() > 0) {
                addProductImgList(product, productImgList);
            }
            return new ProductExecution(ProductStateEnum.SUCCESS, product);
        } else {
            return new ProductExecution(ProductStateEnum.EMPTY);
        }
    }

    @Override
    @Transactional(rollbackFor = ProductOperationException.class)
    public ProductExecution modifyProduct(Product product, ImageHolder thumbnail, List<ImageHolder> productImgList) throws ProductOperationException {
        if (product != null && product.getShop() != null && product.getShop().getShopId() != null) {
            product.setLastEditTime(new Date());
            //若商品缩略图不为空则删除原有缩略图并添加
            if (thumbnail != null) {
                //先获取一遍原有信息
                Product tempProduct = productDao.queryProductById(product.getProductId());
                if (tempProduct != null) {
                    ImageUtil.deleteFileOrPath(tempProduct.getImgAddr());
                }
                addThumbnail(product, thumbnail);
            }
            //判断商品详情图片列表是否有值，有就删掉
            if (productImgList != null && productImgList.size() > 0) {
                deleteProductImgList(product.getProductId());
                addProductImgList(product, productImgList);
            }
            try {
                int rowCount = productDao.updateProduct(product);
                if (rowCount == 0) {
                    throw new ProductOperationException("更新商品信息失败");
                }
                return new ProductExecution(ProductStateEnum.SUCCESS, product);
            } catch (ProductOperationException e) {
                throw new ProductOperationException("modifyProduct error:" + e.toString());
            }
        } else {
            return new ProductExecution(ProductStateEnum.EMPTY);
        }
    }

    /**
     * 删除数据表信息和路径下的图片
     *
     * @param productId
     */
    private void deleteProductImgList(Long productId) {
        List<ProductImg> imgList = productImgDao.queryProductImgList(productId);
        for (ProductImg productImg : imgList) {
            ImageUtil.deleteFileOrPath(productImg.getImgAddr());
        }
        productImgDao.deleteProductImgByProductId(productId);
    }

    @Override
    public ProductExecution getProductList(Product productCondition, int pageIndex, int pageSize) {
        int rowIndex = PageCalculator.calculateRowIndex(pageIndex, pageSize);
        List<Product> productList = productDao.queryProductList(productCondition, rowIndex, pageSize);
        int count = productDao.queryProductCount(productCondition);
        ProductExecution pe = new ProductExecution();
        pe.setProductList(productList);
        pe.setCount(count);
        return pe;
    }

    @Override
    public Product getProductById(long productId) {
        return productDao.queryProductById(productId);
    }

    /**
     * 批量上传图片
     *
     * @param product
     * @param productImgList
     */
    private void addProductImgList(Product product, List<ImageHolder> productImgList) {
        String dest = PathUtil.getShopImagePath(product.getShop().getShopId());
        List<ProductImg> productImgs = new ArrayList<>();
        for (ImageHolder imageHolder : productImgList) {
            String imgAddr = ImageUtil.generateNormalImg(imageHolder, dest);
            ProductImg productImg = new ProductImg();
            productImg.setImgAddr(imgAddr);
            productImg.setCreateTime(new Date());
            productImg.setProductId(product.getProductId());
            productImgs.add(productImg);
        }
        //如果确定有图片需要添加，就执行批量操作
        if (productImgs.size() > 0) {
            try {
                int rowCount = productImgDao.batchInsertProductImg(productImgs);
                if (rowCount == 0) {
                    throw new ProductOperationException("添加批量图片上传失败");
                }
            } catch (Exception e) {
                throw new ProductOperationException("添加批量图片上传失败:" + e.getMessage());
            }
        }
    }

    /**
     * 添加缩略图
     *
     * @param product
     * @param thumbnail
     */
    private void addThumbnail(Product product, ImageHolder thumbnail) {
        String dest = PathUtil.getShopImagePath(product.getShop().getShopId());
        String thumbnailAddr = ImageUtil.generateThumbnail(thumbnail, dest);
        product.setImgAddr(thumbnailAddr);
    }

}
